import { safeInvoke } from './tauri';
import { getSetting, updateSetting } from './settings';

interface NetworkInfo {
  localIp: string;
  httpActive: boolean;
  websocketActive: boolean;
  lastUpdated: number;
}

class IPManager {
  private static instance: IPManager;
  private networkInfo: NetworkInfo | null = null;
  private readonly CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存
  private readonly IP_SETTING_KEY = 'cached_local_ip';
  private readonly IP_TIMESTAMP_KEY = 'cached_ip_timestamp';
  private isUpdating = false;

  private constructor() {}

  static getInstance(): IPManager {
    if (!IPManager.instance) {
      IPManager.instance = new IPManager();
    }
    return IPManager.instance;
  }

  /**
   * 获取本地IP地址（带缓存）
   */
  async getLocalIP(): Promise<string> {
    // 如果正在更新，等待更新完成
    if (this.isUpdating) {
      await this.waitForUpdate();
    }

    // 检查内存缓存
    if (this.networkInfo && this.isCacheValid()) {
      return this.networkInfo.localIp;
    }

    // 检查持久化缓存
    const cachedIP = await this.getCachedIPFromStorage();
    if (cachedIP) {
      this.networkInfo = {
        localIp: cachedIP,
        httpActive: false,
        websocketActive: false,
        lastUpdated: Date.now()
      };
      return cachedIP;
    }

    // 缓存无效或不存在，重新获取
    return await this.refreshIP();
  }

  /**
   * 获取完整的网络信息
   */
  async getNetworkInfo(): Promise<NetworkInfo> {
    const localIp = await this.getLocalIP();
    
    if (!this.networkInfo) {
      this.networkInfo = {
        localIp,
        httpActive: false,
        websocketActive: false,
        lastUpdated: Date.now()
      };
    }

    // 更新服务状态
    await this.updateServiceStatus();
    
    return { ...this.networkInfo };
  }

  /**
   * 强制刷新IP地址
   */
  async refreshIP(): Promise<string> {
    if (this.isUpdating) {
      await this.waitForUpdate();
      return this.networkInfo?.localIp || '获取失败';
    }

    this.isUpdating = true;

    try {
      console.log('正在获取本地IP地址...');
      const ip = await safeInvoke<string>('get_local_ip');
      
      if (ip && ip !== '获取失败') {
        // 更新内存缓存
        this.networkInfo = {
          localIp: ip,
          httpActive: this.networkInfo?.httpActive || false,
          websocketActive: this.networkInfo?.websocketActive || false,
          lastUpdated: Date.now()
        };

        // 保存到持久化存储
        await this.saveCachedIPToStorage(ip);
        
        console.log('IP地址获取成功:', ip);
        return ip;
      } else {
        throw new Error('获取到无效的IP地址');
      }
    } catch (error) {
      console.error('获取IP地址失败:', error);
      
      // 尝试从缓存获取
      const cachedIP = await this.getCachedIPFromStorage();
      if (cachedIP) {
        console.log('使用缓存的IP地址:', cachedIP);
        return cachedIP;
      }
      
      return '获取失败';
    } finally {
      this.isUpdating = false;
    }
  }

  /**
   * 更新服务状态
   */
  async updateServiceStatus(): Promise<void> {
    if (!this.networkInfo) return;

    try {
      // 使用Tauri命令检查服务状态，更可靠
      const httpActive = await safeInvoke<boolean>('check_http_server_status');
      const websocketActive = await safeInvoke<boolean>('check_websocket_server_status');
      
      this.networkInfo.httpActive = httpActive || false;
      this.networkInfo.websocketActive = websocketActive || false;
    } catch (error) {
      console.error('更新服务状态失败:', error);
      this.networkInfo.httpActive = false;
      this.networkInfo.websocketActive = false;
    }
  }

  /**
   * 清除缓存
   */
  async clearCache(): Promise<void> {
    this.networkInfo = null;
    await updateSetting(this.IP_SETTING_KEY, '');
    await updateSetting(this.IP_TIMESTAMP_KEY, '');
  }

  /**
   * 获取格式化的网络地址
   */
  async getFormattedAddresses(): Promise<{
    httpUrl: string;
    websocketUrl: string;
    localIp: string;
  }> {
    const localIp = await this.getLocalIP();
    
    return {
      httpUrl: `http://${localIp}:3030`,
      websocketUrl: `ws://${localIp}:3032`,
      localIp
    };
  }

  /**
   * 检查缓存是否有效
   */
  private isCacheValid(): boolean {
    if (!this.networkInfo) return false;
    
    const now = Date.now();
    const elapsed = now - this.networkInfo.lastUpdated;
    
    return elapsed < this.CACHE_DURATION;
  }

  /**
   * 从存储获取缓存的IP
   */
  private async getCachedIPFromStorage(): Promise<string | null> {
    try {
      const cachedIP = await getSetting(this.IP_SETTING_KEY);
      const timestampStr = await getSetting(this.IP_TIMESTAMP_KEY);
      
      if (!cachedIP || !timestampStr) return null;
      
      const timestamp = parseInt(timestampStr);
      const now = Date.now();
      
      // 检查缓存是否过期
      if (now - timestamp > this.CACHE_DURATION) {
        return null;
      }
      
      return cachedIP;
    } catch (error) {
      console.error('获取缓存IP失败:', error);
      return null;
    }
  }

  /**
   * 保存IP到存储
   */
  private async saveCachedIPToStorage(ip: string): Promise<void> {
    try {
      await updateSetting(this.IP_SETTING_KEY, ip);
      await updateSetting(this.IP_TIMESTAMP_KEY, Date.now().toString());
    } catch (error) {
      console.error('保存缓存IP失败:', error);
    }
  }

  /**
   * 等待更新完成
   */
  private async waitForUpdate(): Promise<void> {
    while (this.isUpdating) {
      await new Promise(resolve => setTimeout(resolve, 100));
    }
  }
}

// 导出单例实例
export const ipManager = IPManager.getInstance();

// 便捷方法
export const getLocalIP = () => ipManager.getLocalIP();
export const getNetworkInfo = () => ipManager.getNetworkInfo();
export const refreshIP = () => ipManager.refreshIP();
export const getFormattedAddresses = () => ipManager.getFormattedAddresses();
export const clearIPCache = () => ipManager.clearCache();
